package cc.vicp.djx314.msing.util.web.impl;

import org.springframework.stereotype.Component;

import cc.vicp.djx314.msing.util.web.EncodeUtil;

@Component
public class EncodeUtilImpl implements EncodeUtil {
	@Override
	public String getStringEncode(String str) {
		String encode = null;
		if (java.nio.charset.Charset.forName(UTF_8).newEncoder().canEncode(str)) {
			encode = UTF_8;
		}
		if (java.nio.charset.Charset.forName(ISO_8859_1).newEncoder().canEncode(str)) {
			encode = ISO_8859_1;
		}
		return encode;
	}

	@Override
	public String getStringUTF_8(String str) {
		try {
			String encode = getStringEncode(str);
			String targetEncoding = UTF_8;
			if (!targetEncoding.equals(encode)) {
				if(encode != null) {
					str = new String(str.getBytes(encode), targetEncoding);
				} else {
					throw new IllegalArgumentException("传入的字符串没有合符的编码");
				}
			}
			return str;
		} catch (Exception e) {
			throw new RuntimeException("转码错误", e);
		}
	}
}